package com.xinjian.jianba.utils;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 日期格式化工具类
 * 
 */
public class DateUtil {

	private static final Logger LOGGER = LoggerFactory.getLogger(DateUtil.class);

	private final static SimpleDateFormat shortSdf = new SimpleDateFormat("yyyy-MM-dd");
	private final static SimpleDateFormat longHourSdf = new SimpleDateFormat("yyyy-MM-dd HH");;
	private final static SimpleDateFormat longSdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	public final static String DATE_FORMAT = "yyyy-MM-dd";
	public static final String YYYY_MM_DD_HH_MM_SS = "yyyy-MM-dd HH:mm:ss";

	/**
	 * 根据格式把日期转换成字符串
	 * 
	 * @param date
	 *            日期
	 * @param template
	 *            格式
	 * @return
	 */
	public static String format(Date date, String template) {
		return new SimpleDateFormat(template).format(date);
	}

	/**
	 * 根据格式把日期转换成Date对象
	 * 
	 * @param date
	 *            日期
	 * @param template
	 *            格式
	 * @return
	 * @throws ParseException
	 */
	public static Date parse(String template, String date) {
		if (StringUtils.isBlank(date)) {
			return null;
		}
		try {
			return new SimpleDateFormat(template).parse(date);
		} catch (ParseException e) {
			LOGGER.info("date parse exception ---" + e);
		}
		return null;
	}

	/***
	 * 获取两个月份之间的月份字符串
	 * 
	 * @author Michael.Zhang
	 * @param begMonth
	 *            开始月份
	 * @param endMonth
	 *            结束月份
	 * @param template
	 * @return
	 */
	public static String monthToMonthStr(String begMonth, String endMonth, String template) throws Exception {
		SimpleDateFormat dateFarmot = new SimpleDateFormat(template, Locale.CHINA);
		Date beMonth = dateFarmot.parse(begMonth);
		Date enMonth = dateFarmot.parse(endMonth);
		StringBuffer monthStr = new StringBuffer("'" + begMonth + "'");
		while (enMonth.compareTo(beMonth) >= 0) {
			Calendar befor = Calendar.getInstance();
			befor.setTime(beMonth);
			befor.add(Calendar.MONTH, 1);
			beMonth = befor.getTime();
			if (beMonth.compareTo(enMonth) <= 0) {
				monthStr.append(",'" + dateFarmot.format(beMonth) + "'");
			}
		}
		return monthStr.substring(0, monthStr.length());
	}

	/**
	 * 计算两个日期之间相差的天数
	 * 
	 * @param beginDate
	 *            开始时间
	 * @param endDate
	 *            结束时间
	 * @return int 天数
	 * @throws ParseException
	 */
	public static Integer daysBetween(Date beginDate, Date endDate) throws ParseException {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		beginDate = sdf.parse(sdf.format(beginDate));
		endDate = sdf.parse(sdf.format(endDate));
		Calendar cal = Calendar.getInstance();
		cal.setTime(beginDate);
		long time1 = cal.getTimeInMillis();
		cal.setTime(endDate);
		long time2 = cal.getTimeInMillis();
		long between_days = (time2 - time1) / (1000 * 3600 * 24);
		return Integer.parseInt(String.valueOf(between_days));
	}

	/**
	 * @description 根据日期和指定格式返回对应格式的date类型数据
	 * @date: 2016年10月24日 下午2:48:18
	 * @author 胖黑
	 * @param aDate
	 * @param template
	 * @return
	 * @throws ParseException
	 */
	public static final Date getDateToDate(Date aDate, String template) {
		SimpleDateFormat df = null;
		String returnValue = "";
		Date date = null;
		if (aDate != null) {
			df = new SimpleDateFormat(template);
			returnValue = df.format(aDate);
			try {
				date = df.parse(returnValue);
			} catch (ParseException e) {
				LOGGER.info("getDateToDate ---exception", e.getMessage());
				return date;
			}
		}
		return date;
	}

	/***
	 * 判断当前时间是否在给定时间之间
	 * 
	 * @date: 2016年10月24日 上午11:38:02
	 * @author 胖黑
	 * @param startTime
	 * @return boolean
	 * @throws ParseException
	 */
	public static boolean isBetweenTime(String startTime, String endTime) throws ParseException {
		boolean istrue = false;
		if (null == startTime || null == endTime) {
			return false;
		}
		Date startDate = DateUtil.parse("yyyy-MM-dd HH:mm:ss", startTime + " 00:00:00");
		Date endDate = DateUtil.parse("yyyy-MM-dd HH:mm:ss", endTime + " 23:59:59");
		Date nowDate = new Date();
		if (startDate.getTime() <= nowDate.getTime() && endDate.getTime() >= nowDate.getTime()) {
			istrue = true;
		}
		return istrue;
	}

	public static boolean isBetweenTime(Date startTime, Date endTime) {
		boolean istrue = false;
		if (null == startTime || null == endTime) {
			return false;
		}
		Date nowDate = new Date();
		if (startTime.getTime() <= nowDate.getTime() && endTime.getTime() >= nowDate.getTime()) {
			istrue = true;
		}
		return istrue;
	}

	/**
	 * @description 当前时间是否大于给定时间
	 * @date: 2016年10月24日 上午11:38:02
	 * @author 胖黑
	 * @param startTime
	 *            与系统时间比较的时间
	 * @param templt
	 *            时间格式yyyy-mm-dd hh:mm:ss
	 * @return boolean
	 * @throws ParseException
	 */
	public static boolean isBeforeTime(String startTime, String templt) throws ParseException {
		boolean istrue = false;
		if (null == startTime) {
			return false;
		}
		Date startDate = DateUtil.parse(templt, startTime);
		Date nowDate = new Date();
		if (startDate.getTime() < nowDate.getTime()) {
			istrue = true;
		}
		return istrue;
	}

	public static boolean isBeforeTime(Date startTime) {
		boolean istrue = false;
		if (null == startTime) {
			return false;
		}
		Date nowDate = new Date();
		if (startTime.getTime() < nowDate.getTime()) {
			istrue = true;
		}
		return istrue;
	}

	/**
	 * 当前季度的开始时间
	 * 
	 * @return
	 * @throws ParseException
	 */
	public static Date getCurrentQuarterStartTime() throws ParseException {
		Calendar c = Calendar.getInstance();
		int currentMonth = c.get(Calendar.MONTH) + 1;
		Date now = null;
		if (currentMonth >= 1 && currentMonth <= 3)
			c.set(Calendar.MONTH, 0);
		else if (currentMonth >= 4 && currentMonth <= 6)
			c.set(Calendar.MONTH, 3);
		else if (currentMonth >= 7 && currentMonth <= 9)
			c.set(Calendar.MONTH, 6);
		else if (currentMonth >= 10 && currentMonth <= 12)
			c.set(Calendar.MONTH, 9);
		c.set(Calendar.DATE, 1);
		now = longSdf.parse(shortSdf.format(c.getTime()) + " 00:00:00");
		return now;
	}

	/**
	 * 当前季度的结束时间
	 * 
	 * @return
	 * @throws ParseException
	 */
	public static Date getCurrentQuarterEndTime() throws ParseException {
		Calendar c = Calendar.getInstance();
		int currentMonth = c.get(Calendar.MONTH) + 1;
		Date now = null;
		if (currentMonth >= 1 && currentMonth <= 3) {
			c.set(Calendar.MONTH, 2);
			c.set(Calendar.DATE, 31);
		} else if (currentMonth >= 4 && currentMonth <= 6) {
			c.set(Calendar.MONTH, 5);
			c.set(Calendar.DATE, 30);
		} else if (currentMonth >= 7 && currentMonth <= 9) {
			c.set(Calendar.MONTH, 8);
			c.set(Calendar.DATE, 30);
		} else if (currentMonth >= 10 && currentMonth <= 12) {
			c.set(Calendar.MONTH, 11);
			c.set(Calendar.DATE, 31);
		}
		now = longSdf.parse(shortSdf.format(c.getTime()) + " 23:59:59");
		return now;
	}

	/**
	 * 给指定(d)的日期添加指定(skipDay)的天数
	 * 
	 * @param d
	 * @param skipDay
	 *            需要添加的天数，可以为正数或负数
	 * @return
	 */
	public static Date skipDateTime(Date d, int skipDay) {
		if (d == null)
			return null;
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(d);
		calendar.add(Calendar.DATE, skipDay);
		return calendar.getTime();
	}

	public static int compare_date(String DATE1, String DATE2) {

		DateFormat df = new SimpleDateFormat("yyyy-MM-dd hh:mm");
		try {
			Date dt1 = df.parse(DATE1);
			Date dt2 = df.parse(DATE2);
			if (dt1.getTime() > dt2.getTime()) {
				return 1;
			} else if (dt1.getTime() < dt2.getTime()) {
				return -1;
			} else {
				return 0;
			}
		} catch (Exception exception) {
			exception.printStackTrace();
		}
		return 0;
	}

	// 出生日期字符串转化成Date对象
	public static Date parse(String strDate) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		try {
			return sdf.parse(strDate);
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

	// 由出生日期获得年龄
	public static int getAge(Date birthDay) {
		if (birthDay == null) {
			return 20;
		}
		Calendar cal = Calendar.getInstance();

		if (cal.before(birthDay)) {
			throw new IllegalArgumentException("The birthDay is before Now.It's unbelievable!");
		}
		int yearNow = cal.get(Calendar.YEAR);
		int monthNow = cal.get(Calendar.MONTH);
		int dayOfMonthNow = cal.get(Calendar.DAY_OF_MONTH);
		cal.setTime(birthDay);

		int yearBirth = cal.get(Calendar.YEAR);
		int monthBirth = cal.get(Calendar.MONTH);
		int dayOfMonthBirth = cal.get(Calendar.DAY_OF_MONTH);

		int age = yearNow - yearBirth;

		if (monthNow <= monthBirth) {
			if (monthNow == monthBirth) {
				if (dayOfMonthNow < dayOfMonthBirth)
					age--;
			} else {
				age--;
			}
		}
		return age;
	}

	private final static int[] dayArr = new int[] { 20, 19, 21, 20, 21, 22, 23, 23, 23, 24, 23, 22 };
	private final static String[] constellationArr = new String[] { "摩羯座", "水瓶座", "双鱼座", "白羊座", "金牛座", "双子座", "巨蟹座", "狮子座", "处女座", "天秤座",
			"天蝎座", "射手座", "摩羯座" };

	public static String getConstellation(Date date) {

		Calendar cal = Calendar.getInstance();

		cal.setTime(date);

		int monthBirth = cal.get(Calendar.MONTH) + 1;
		int dayOfMonthBirth = cal.get(Calendar.DAY_OF_MONTH);
		return dayOfMonthBirth < dayArr[monthBirth - 1] ? constellationArr[monthBirth - 1] : constellationArr[monthBirth];
	}

	/**
	 * java.util.Date 转 yyyy-MM-dd HH:mm:ss
	 * @param date
	 * @return
	 */
	public static String utilDateToTimestampString(java.util.Date date){
		SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		return sf.format(date);
	}
	/**
	 * java.util.Date 转 yyyy-MM-dd
	 * @param date
	 * @return
	 */
	public static String utilDateToString(java.util.Date date){
		SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
		return sf.format(date);
	}
	/**
	 * 计算 minute 分钟后的时间
	 * 
	 * @param date
	 * @param minute
	 * @return
	 */
	public static Date addMinute(Date date, int minute) {
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(date);
		calendar.add(Calendar.MINUTE, minute);
		return calendar.getTime();
	}

	/**
	 * 将日期对象按照某种格式进行转换，返回转换后的字符串
	 * 
	 * @param date 		日期格式对象
	 * @param pattern 	转换格式 形如：yyyy-MM-dd HH:mm:ss 若pattern为空，则默认转换为yyyy-MM-dd HH:mm:ss形式
	 */
	public static String DateToString(Date date, String pattern) {
		if (date == null) {
			return "";
		}

		if (pattern == null || "".equals(pattern)) {
			pattern = YYYY_MM_DD_HH_MM_SS;
		}

		SimpleDateFormat formater = new SimpleDateFormat(pattern);
		return formater.format(date);

	}
}
